package handler

import (
	"context"
	"fmt"
	"log"
	"user-server/global"
	"user-server/model"
	__ "user-server/proto"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) ListOrder(_ context.Context, in *__.ListOrderRequest) (*__.ListOrderResponse, error) {
	var ListOrder []model.Orders
	global.DB.Debug().Find(&ListOrder)
	var list []*__.ListOrder
	for _, v := range ListOrder {
		list = append(list, &__.ListOrder{
			UserId: int64(v.UserId),
			Name:   v.Name,
			Price:  float32(v.Price),
			Status: v.Status,
		})
	}
	return &__.ListOrderResponse{List: list}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) AddOrder(_ context.Context, in *__.AddOrderRequest) (*__.AddOrderResponse, error) {
	var order model.Orders
	global.DB.Debug().Where("name=?", in.Name).Find(&order)
	if order.Id != 0 {
		return nil, fmt.Errorf("订单商品已存在")
		log.Printf("订单商品已存在")
	}
	orders := model.Orders{
		UserId: uint(in.UserId),
		Name:   in.Name,
		Price:  float64(in.Price),
		Status: in.Status,
	}
	global.DB.Create(&orders)
	return &__.AddOrderResponse{}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) BuyOrder(_ context.Context, in *__.BuyOrderRequest) (*__.BuyOrderResponse, error) {
	var order model.Orders
	global.DB.Debug().Where("name=?", in.Name).Find(&order)
	if order.Id != 0 {
		return nil, fmt.Errorf("订单商品已存在")
		log.Println("订单商品已存在")
	}
	orders := model.Orders{
		UserId: uint(in.UserId),
		Name:   in.Name,
		Price:  float64(in.Price),
		Status: in.Status,
	}
	global.DB.Create(&orders)
	return &__.BuyOrderResponse{}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Like(_ context.Context, in *__.LikeRequest) (*__.LikeResponse, error) {
	var Like []model.Likes
	global.DB.Debug().Order("desc like").Find(&Like)
	var list []*__.Like
	for _, v := range Like {
		list = append(list, &__.Like{
			Name:   v.Name,
			UserId: int64(v.UserId),
			Like:   int64(v.Like),
		})
	}
	return &__.LikeResponse{
		List: list,
	}, nil
}
